import moment from 'moment'
import router from '@/router'
import { i18nRender } from '../locales' // 注意循环引用

export function timeFix () {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9
    ? i18nRender('all.autotext1356.1')
    : hour <= 11
    ? i18nRender('all.autotext1356.2')
    : hour <= 13
    ? i18nRender('all.autotext1356.3')
    : hour < 20
    ? i18nRender('all.autotext1356.4')
    : i18nRender('all.autotext1356.5')
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE () {
  const bw = window.navigator.userAgent
  const compare = s => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}
export function scorePassword (pass) {
  let score = 0
  if (!pass) {
    return score
  }
  // award every unique letter until 5 repetitions
  const letters = {}
  for (let i = 0; i < pass.length; i++) {
    letters[pass[i]] = (letters[pass[i]] || 0) + 1
    score += 5.0 / letters[pass[i]]
  }

  // bonus points for mixing it up
  const variations = {
    digits: /\d/.test(pass),
    lower: /[a-z]/.test(pass),
    upper: /[A-Z]/.test(pass),
    nonWords: /\W/.test(pass)
  }

  let variationCount = 0
  for (let check in variations) {
    variationCount += variations[check] === true ? 1 : 0
  }
  score += (variationCount - 1) * 10

  return parseInt(score)
}

export function exportExcel (key, data, time) {
  let name = key + moment().format('YYYY-MM-DD')
  if (time) name = key
  let fileName = `${name}.xlsx`
  let exporturl = window.URL.createObjectURL(
    new Blob([data], { type: 'application/octet-stream' })
  )
  let a = document.createElement('a')
  document.body.appendChild(a)
  a.href = exporturl
  a.download = fileName
  a.target = '_blank'
  a.click()
  document.body.removeChild(a)
}

export function exportPdf (key, data) {
  const name = key
  let fileName = `${name}.pdf`
  let exporturl = window.URL.createObjectURL(
    new Blob([data], { type: 'application/pdf' })
  )
  let a = document.createElement('a')
  document.body.appendChild(a)
  a.href = exporturl
  a.download = fileName
  a.target = '_blank'
  a.click()
  document.body.removeChild(a)
}

/**
 * 从接口返回的二进制数据导出
 * @param fileName
 * @param data ArrayBuffer
 */
export function exportBlob (fileName, data) {
  let exportUrl = window.URL.createObjectURL(
    new Blob([data], { type: 'application/octet-stream' })
  )
  let a = document.createElement('a')
  document.body.appendChild(a)
  a.style.display = 'none'
  a.href = exportUrl
  a.download = fileName
  a.target = '_blank'
  a.click()
  document.body.removeChild(a)
}

/**
 * 下载二进制文件
 * @param fileName
 * @param {Blob} blob
 */
export function downloadBlob (fileName, blob) {
  const downloadUrl = window.URL.createObjectURL(blob)
  let a = document.createElement('a')
  document.body.appendChild(a)
  a.style.display = 'none'
  a.href = downloadUrl
  a.download = fileName
  a.target = '_blank'
  a.click()
  document.body.removeChild(a)
}

/**
 * 转为非响应式对象
 * @param data
 * @return *
 */
export function unreactive (data) {
  return Object.freeze(data)
}

/**
 * 从响应头获取文件名
 * @param headers 响应头
 * @param defaultSuffix 默认的后缀
 * @return {string|string}
 */
export function getFileNameByResponse (headers = {}, defaultSuffix = 'xlsx') {
  return decodeURIComponent(
    headers['content-disposition']?.split(';')?.[1].split('filename=')?.[1] ||
      `${i18nRender('all.autotext998')}.${defaultSuffix}`
  )
}

/**
 * dataUrl 转 blob
 * @param {string} dataUrl
 * @return {Blob}
 */
export function dataUrlToBlob (dataUrl) {
  if (!dataUrl) throw new Error('dataUrlToBlob Error：请传入dataUrl')
  const [binaryType, base64Str] = dataUrl.split(',')
  const mimeType = binaryType.match(/[\w/]+(?=;base64)/)[0]
  const binaryStr = window.atob(base64Str)
  let binaryStrLen = binaryStr.length
  const u8a = new Uint8Array(binaryStrLen)
  while (binaryStrLen) {
    binaryStrLen--
    u8a[binaryStrLen] = binaryStr.charCodeAt(binaryStrLen)
  }
  return new Blob([u8a], { type: mimeType })
}

/**
 * 导航到目标地址，如果是外链直接打开，如果是内链则跳转
 * @param url
 */
export function navigateTo (url) {
  if (!url) throw new Error(this.$t('all.autotext1445'))
  if (url.startsWith('http') || url.startsWith('//')) {
    window.local.href = url
  } else {
    router.push(url)
  }
}

/**
 * base64 转 blob
 * @param dataurl
 * @return {Blob}
 */
export function dataURLtoBlob (dataurl) {
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

export const exportZipcom = (key, data) => {
  const name = key
  let fileName = `${name}.zip`
  let exporturl = window.URL.createObjectURL(
    new Blob([data], { type: 'application/zip' })
  )
  let a = document.createElement('a')
  document.body.appendChild(a)
  a.href = exporturl
  a.download = fileName
  a.target = '_blank'
  a.click()
  document.body.removeChild(a)
}

export const getUrlQuery = url => {
  // str为？之后的参数部分字符串
  const str = url.substr(url.indexOf('?') + 1)
  // arr每个元素都是完整的参数键值
  const arr = str.split('&')
  // result为存储参数键值的集合
  const result = {}
  for (let i = 0; i < arr.length; i++) {
    // item的两个元素分别为参数名和参数值
    const item = arr[i].split('=')
    result[item[0]] = decodeURIComponent(item[1])
  }
  return result
}
